<template>
  <view class="push-container">
    <view class="main-container">
      <view class="store-tip">
        <img src="～@/static/order_push_slices/1133.png" alt="">
<!--        <text>阳陂湖</text>-->
      </view>
      <view class="title-container">
        {{ title }}
      </view>
      <view class="store-tip">
        <text>需预约</text>
        <!-- <img src="～@/static/order_push_slices/1133.png" alt="">
        <text class="right">半年消费 4590</text> -->
      </view>
      <view class="mainimg-container">
        <img :src="imgUrl" alt="">
      </view>
      <view class="time-select-container">
        <view class="time-option-container" :class="appointmentData === parseTime(new Date(), '{y}-{m}-{d}') ? 'active' : ''" @click="clickAppointmentData(parseTime(new Date(), '{y}-{m}-{d}'))">
          <view class="data">{{ parseTime(new Date(), "{y}-{m}-{d}") }}</view>
          <view class="data">今天</view>
        </view>
        <view class="time-option-container" :class="appointmentData === parseTime(getDate(1), '{y}-{m}-{d}') ? 'active' : ''" @click="clickAppointmentData(parseTime(getDate(1), '{y}-{m}-{d}'))">
          <view class="data">{{ parseTime(getDate(1), "{y}-{m}-{d}") }}</view>
          <view class="data">{{ getWeek(getDate(1).getDay()) }}</view>
        </view>
        <view class="time-option-container" :class="appointmentData === parseTime(getDate(2), '{y}-{m}-{d}') ? 'active' : ''" @click="clickAppointmentData(parseTime(getDate(2), '{y}-{m}-{d}'))">
          <view class="data">{{ parseTime(getDate(2), "{y}-{m}-{d}") }}</view>
          <view class="data">{{ getWeek(getDate(2).getDay()) }}</view>
        </view>
        <view class="time-option-container" :class="appointmentData === parseTime(getDate(3), '{y}-{m}-{d}') ? 'active' : ''" @click="clickAppointmentData(parseTime(getDate(3), '{y}-{m}-{d}'))">
          <view class="data">{{ parseTime(getDate(3), "{y}-{m}-{d}") }}</view>
          <view class="data">{{ getWeek(getDate(3).getDay()) }}</view>
        </view>
        <view class="time-option-container" :class="appointmentData === parseTime(getDate(4), '{y}-{m}-{d}') ? 'active' : ''" @click="clickAppointmentData(parseTime(getDate(4), '{y}-{m}-{d}'))">
          <view class="data">{{ parseTime(getDate(4), "{y}-{m}-{d}") }}</view>
          <view class="data">{{ getWeek(getDate(4).getDay()) }}</view>
        </view>
        <view class="time-option-container" :class="appointmentData === parseTime(getDate(5), '{y}-{m}-{d}') ? 'active' : ''" @click="clickAppointmentData(parseTime(getDate(5), '{y}-{m}-{d}'))">
          <view class="data">{{ parseTime(getDate(5), "{y}-{m}-{d}") }}</view>
          <view class="data">{{ getWeek(getDate(5).getDay()) }}</view>
        </view>
      </view>
      <view class="form-container">
        <view class="form-item">
          <view class="label">数量</view>
          <view class="contrl">
            <view class="count-ctrl">
              <text class="iconfont icon-minus" @click="quantity > 0 ? quantity-- : ''"></text>
              <text class="count">{{ quantity }}</text>
              <text class="iconfont icon-plus" @click="quantity++"></text>
            </view>
          </view>
        </view>
        <view class="form-item">
          <view class="contrl">
            <text v-html="details"></text>
          </view>
        </view>
        <view class="form-item">
          <view class="label">{{ title }}</view>
          <view class="contrl">
            <view class="list">
              <view class="item">
                <text class="type">单份</text>
                <text class="detail">{{ price }}元</text>
              </view>
              <view class="item">
                <text class="type">总价</text>
                <text class="detail">{{ price * quantity }}元</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="message-container">
        <!--
        <text>通知：需要园区提前预约 预约电话 12346778（佩戴 口罩、携带身份证）<br />1、选择安全水域路线<br />2、每张门票限时使用2小时</text>
        -->
      </view>
    </view>
    <view class="footer-container">
      <view class="price">
        <text style="color: #999999; font-size: 14px;">¥</text>
        <text style="color: #FFB838">{{ price * quantity }}</text>
        <text style="color: #999999; font-size: 14px; margin-left: 5px; text-decoration: line-through;">门市价 ¥{{ marketPrice * quantity }}</text>
      </view>
      <view class="action-btn" :class="quantity < 1 ? 'disabled' : ''" @click="pushOrder">立即抢购</view>
    </view>
  </view>
</template>
<script lang="ts">
import Vue from 'vue';
import { getQuery, parseMD5, parseTime } from "@/util/common";
import { token } from '@/util/storage';

export default Vue.extend({
  data() {
    return {
      productId: "",
      appointmentData: parseTime(new Date(), "{y}-{m}-{d}"),
      title: "",
      imgUrl: "",
      marketPrice: 0,
      price: 0,
      quantity: 0,
      details: "",
    };
  },
  computed: {
    parseTime: () => parseTime,
    redirect() {
      return encodeURI("/pages/order/push?id=" + getQuery().id);
    }
  },
  mounted() {
    this.productId = getQuery().id;
    this.getProductInfo();
  },
  methods: {
    toBack() {
      uni.navigateBack({ delta: 1 })
    },
    bgDynamic() {},
    getDate(i: number) {
      return new Date(new Date().getTime() + (i * 24 * 60 * 60 * 1000))
    },
    getWeek(i: number) {
      return ({ 0: '星期天', 1: "星期一", 2: "星期二", 3: "星期三", 4: "星期四", 5: "星期五", 6: "星期六" } as any)[i];
    },
    getProductInfo() {
      this.$mainApi.apiGetProductDetail(this.productId).then(res => {
        console.log(res.data);
        this.title = res.data.title;
        this.imgUrl = res.data.imageUrl;
        this.marketPrice = res.data.marketPrice;
        this.price = res.data.price;
        this.details = res.data.details
      });
    },
    clickAppointmentData(date: string) {
      console.log(date);
      this.appointmentData = date;
    },
    wechatRandom() {
      const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
      const maxPos = $chars.length;
      let pwd = '';
      for (let i = 0; i < 32; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    },
    wechatSign(data: any) {
      const paramArr = [];
      let stringA = "";
      for (const name in data) {
        paramArr.push({ label: name, value: data[name] });
      }

      paramArr.sort((paramA, paramB) => { return paramA.label.charCodeAt(0) - paramB.label.charCodeAt(0) });
      paramArr.forEach((param: any) => { stringA += param.label + "=" + param.value + "&" });

      const stringSignTemp = stringA+"key=" + this.$config.WEIXIN_PAY_KEY;

      console.log(stringSignTemp);

      const sign = parseMD5(stringSignTemp).toUpperCase()

      return sign;
    },
    pushOrder() {
      if (this.quantity < 1) return;

      if (!token.get()) {
        location.href = '/#/pages/login/wechat?redirect=' + this.redirect;
      }

      this.$mainApi.apiPushOrder({
        "appointmentdAt": this.appointmentData,
        "paidThrough": 1,
        "productId": this.productId,
        "quantity": this.quantity,
        "trade_type": "JSAPI"
      }).then((res) => {
        const invokeData: any = {
          "appId": res.data.appid,     //公众号名称，由商户传入
          "timeStamp": parseInt((new Date().getTime() / 1000).toString()).toString(),         //时间戳，自1970年以来的秒数
          "nonceStr": this.wechatRandom(), //随机串
          "package": "prepay_id=" + res.data.prepay_id,
          "signType": res.data.signType
        };

        const paySign = this.wechatSign(invokeData);

        invokeData.paySign = paySign;

        console.log(invokeData);

        (window as any).WeixinJSBridge.invoke(
          'getBrandWCPayRequest', invokeData,
          function(payResult: any){
            console.log(payResult);
            if(payResult.err_msg == "get_brand_wcpay_request:ok" ){
              uni.showToast({
                title: "微信支付成功",
              });
            } else {
              uni.showToast({
                title: "微信支付失败",
              });
            }
            location.href = "/#/pages/order/detail?id=" + res.data.id;
          }
        );
      });
    }
  }
})
</script>
<style>
.push-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.header-container {
  color: #fff;
  height: 24px;
  padding: 15px;
  flex-shrink: 0;
  display: flex;
  background: #006b65;
}

.header-container .left,
.header-container .right {
  font-size: 16px;
  width: 100px;
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.header-container .center {
  flex-grow: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.main-container {
  flex-grow: 1;
  overflow: auto;
}

.store-tip {
  display: flex;
  padding: 0px 15px;
}

.store-tip img {
  width: 8px;
  height: 8px;
  flex-shrink: 0;
}

.store-tip text {
  color: #999999;
  font-size: 12px;
}

.store-tip .right {
  flex-grow: 1;
  text-align: right;
}

.title-container {
  color: #333333;
  font-size: 24px;
  padding: 5px 15px;
}

.mainimg-container {
  padding: 15px;
}

.mainimg-container img {
  width: 100%;
  border-radius: 8px;
}

.time-select-container {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.time-option-container {
  color: #333333;
  font-size: 12px;
  width: 24%;
  padding: 10px;
  border: 1px solid #999999;
  border-radius: 8px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  flex-shrink: 0;
  margin-bottom: 15px;
  background-color: #FFFFFF;
}

.time-option-container.active {
  color: #FFFFFF;
  background-color: #FFB838;
  border-color: #FFB838;
}

.form-container {
  display: flex;
  flex-direction: column;
  padding: 15px;
}

.form-container .form-item {
  padding: 15px 0px;
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #cccccc;
}

.form-container .form-item .label {
  color: #333333;
  font-size: 16px;
}

.count-ctrl {
  width: 100px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.count-ctrl .iconfont {
  font-size: 16px;
  width: 18px;
  height: 18px;
  text-align: center;
  line-height: 18px;
  border-radius: 9px;
}

.count-ctrl .iconfont.icon-plus {
  color: #FFFFFF;
  background-color: #006b65;
}

.count-ctrl .count {
  color: #333333;
  font-size: 16px;
}

.uni-textarea-placeholder {
  font-size: 16px;
}

.list {
  display: flex;
  flex-direction: column;
}

.list .item {
  display: flex;
  justify-content: space-between;
}

.list .item .type {
  color: #666666;
  font-size: 16px;
}

.list .item .detail {
  color: #333333;
  font-size: 16px;
}

.list .item .detail.im {
  color: #FFB838;
}

.message-container {
  color: #666666;
  font-size: 16px;
  padding: 15px;
}
.footer-container {
  height: 40px;
  padding: 10px 15px;
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.footer-container .pirce {
  color: #666666;
  font-size: 16px;
}

.footer-container .action-btn {
  color: #FFFFFF;
  font-size: 16px;
  background: #006b65;
  padding: 5px;
  border-radius: 8px;
}

.footer-container .action-btn.disabled {
  color: #FFFFFF;
  background-color: #abbfbf;
}
</style>
